package com.abel.quiz.security;/**
 * Created by abel.lin on 2017/8/4.
 */
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.abel.quiz.common.Constants;
import com.abel.quiz.common.ContextUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
/**
 * @author abel.lin
 * @date_time 2017/8/4 14:37
 * @description
 */
public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        String username = obtainUsername(request);
        String password = obtainPassword(request);

        if (username == null) {
            username = "";
        }

        if (password == null) {
            password = "";
        }

        username = username.trim();

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        //登录验证码，如需要开启把下面注释去掉则可
        String captchaCode = StringUtils.defaultString(request.getParameter("captchaCode"));
        String validCode = (String)request.getSession().getAttribute(Constants.captchaCode);
        if(StringUtils.isNotBlank(validCode) && !validCode.equals(captchaCode)){
            ContextUtil.setRequestAttr(Constants.loginCode, Constants.LoginErrorCode.captchaError);
            throw new AuthenticationServiceException("validCode.auth.fail");
        }

        return this.getAuthenticationManager().authenticate(authRequest);
    }
}